import re
from wtforms.fields import StringField, PasswordField, IntegerField
from wtforms.validators import ValidationError


class ValidateMixin(object):

    def check_mobile(self, field, need=True):
        ret = re.match(r"^1[35678]\d{9}$", field.data)
        if not ret:
            raise ValidationError(u'电话号码必须11位且为数字')


class MyIntegerField(IntegerField):
    def __init__(self, label=None, validators=None, message='必须是数字', **kwargs):
        self.message = message
        super(MyIntegerField, self).__init__(label, validators, **kwargs)

    def process_formdata(self, valuelist):
        if valuelist:
            try:
                self.data = int(valuelist[0])
            except ValueError:
                raise ValueError(self.message)
